package com.sahyadri.web.util.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * Utility methods for user credentials
 * 
 * 
 */
public class UserCredentialUtils {

	/**
	 * Gets the user name.
	 * 
	 * @return the user name
	 */
	public static String getUsername() {

		UserDetails userDetails = getUserDetails();
		return userDetails.getUsername();

	}

	/**
	 * Static utility method used to pull the UserDetails object from the Spring
	 * Security Context
	 * 
	 * @return Returns the UserDetails object retrieved from teh SecurityContext
	 * @throws IllegalStateException
	 *             If any of the following conditions occur:
	 *             <ul>
	 *             <li>The current {@link SecurityContext} is null.
	 *             <li>The {@link Authentication} contained in the
	 *             SecurityContext is null;
	 *             <li>The principal object returned from {@link Authentication}
	 *             .getPrincipal() is not an instance of {@link UserDetails}
	 *             </ul>
	 */
	public static UserDetails getUserDetails() {

		SecurityContext ctx = SecurityContextHolder.getContext();
		if (ctx == null) {
			throw new IllegalStateException("Unable to retrieve UserDetails: SecurityContext was null.");
		}

		Authentication auth = ctx.getAuthentication();
		if (auth == null) {
			throw new IllegalStateException("Unable to retrieve UserDetails: Authentication object was null.");
		}

		Object principal = auth.getPrincipal();

		if (principal instanceof UserDetails) {
			return (UserDetails) principal;
		} else {
			throw new IllegalStateException("Unable to retrieve UserDetails: Object returned by getPrincipal ('"
					+ principal + "') was not an instance of UserDetails.");
		}

	}
}
